/*
 * @Description: 弹窗拖拽指令
 */

const dialogDrag = {}

dialogDrag.install = function (Vue, option = {}) {
  Vue.directive('dialogDrag', {
    bind(el) {
      /* eslint-disable */
      const $win = $(window)
      const $doc = $(document)
      const $el = $(el)
      /* eslint-enable */
      const $dialog = $el.find('.el-dialog')
      const $dialogHeader = $dialog.find('.el-dialog__header')
      const dialog = $dialog[0]

      $dialogHeader
        .css({
          cursor: 'move',
          'user-select': 'none',
        })
        .on('mousedown', (evt) => {
          // 考虑到可能会拖动窗口大小，每次都获取最新宽高
          const winWidth = $win.width()
          const winHeight = $win.height()

          const { clientX: startX, clientY: startY } = evt

          const style = getComputedStyle(dialog) || dialog.currentStyle
          const startLeft = parseFloat(style.left)
          const startTop = parseFloat(style.top)

          const { left, top } = $dialog.position()
          const dlgWidth = $dialog.outerWidth(true)
          const dlgHeight = $dialog.outerHeight(true)

          let docMouseMoveHandler = (evt) => {
            const { clientX, clientY } = evt
            let moveX = clientX - startX
            let moveY = clientY - startY

            moveX = Math.min(winWidth - dlgWidth - left, Math.max(moveX, -left))
            moveY = Math.min(winHeight - dlgHeight - top, Math.max(moveY, -top))

            $dialog.css({
              left: startLeft + moveX,
              top: startTop + moveY,
            })
          }
          $doc.on('mousemove', docMouseMoveHandler)

          let docMouseUpHandler = () => {
            $doc.off('mousemove', docMouseMoveHandler)
            docMouseMoveHandler = null
            $doc.off('mouseup', docMouseUpHandler)
            docMouseUpHandler = null
          }
          $doc.on('mouseup', docMouseUpHandler)
        })
    },
  })
}

export default dialogDrag
